package com.linkme2night.model;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import java.io.StringWriter;


import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.*;

public class CreateXml {
  
        
    public static void CreateXml(String e, String[] c, String d[]) throws IOException{
		XmlCon XmlCon = new XmlCon();
        XmlCon.LoadFile();
        Document doc = XmlCon.getDoc();
        StreamResult result = null;
        
         
       NodeList nodes = doc.getElementsByTagName(e);
       Element p = doc.createElement(e); 
       
          for(int j = 0; j <c.length; j++)
          {
          Element e1 = doc.createElement(c[j]);
          e1.appendChild(doc.createTextNode(d[j]));
          p.appendChild(e1);
        }
        
        nodes.item(0).getParentNode().insertBefore(p, nodes.item(0));
        
    try{   
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
        
            result =  new StreamResult(new StringWriter());
            
          //t.setParameter(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
            transformer.transform(source, result);
        }
             catch (Exception o) {
                    o.printStackTrace();
                }
       
          //writing to file
          FileOutputStream fop = null;
          File file;
          try {

                file = new File("res/raw/lm2n.xml");
                fop = new FileOutputStream(file);

                // if file doesnt exists, then create it
                if (!file.exists()) {
                    file.createNewFile();
                }

                // get the content in bytes
                String xmlString = result.getWriter().toString();
                System.out.println(xmlString);
                byte[] contentInBytes = xmlString.getBytes();

                fop.write(contentInBytes);
                fop.flush();
                fop.close();

                System.out.println("Done");

            } catch (IOException o) {
                o.printStackTrace();
            } finally {
                try {
                    if (fop != null) {
                        fop.close();
                    }
                } catch (IOException o) {
                    o.printStackTrace();
                }
            }

    }
}



